﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace MingYuanYun.Primitives
{
    public static class EnumExtensions
    {
	    private static readonly object Mutex = new object();

	    private static readonly Dictionary<Type, Dictionary<object, string>> Cache =
		    new Dictionary<Type, Dictionary<object, string>>();

	    public static string GetDescription(this Enum value)
	    {
		    var type = value.GetType();
		    Dictionary<object, string> typeCache;
		    string desc;

		    if (Cache.TryGetValue(type, out typeCache))
			    if (typeCache.TryGetValue(value, out desc))
				    return desc;

		    lock (Mutex)
		    {
			    if (!Cache.ContainsKey(type))
					Cache[type] = new Dictionary<object, string>();

			    var attribute = (DescriptionAttribute)type
				    .GetRuntimeField(value.ToString())
				    .GetCustomAttributes(typeof(DescriptionAttribute), false)
				    .FirstOrDefault();

			    desc = attribute == null ? value.ToString() : attribute.Description;
			    Cache[type][value] = desc;

			    return desc;
		    }
	    }
	}
}
